/*
 * Copyright (c) 2017 22420103@QQ.COM 版权所有
 */

package com.lehe.common.utils;

import com.lehe.common.Contants;
import org.apache.commons.lang.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 字符串工具类型。<br>
 * @see org.apache.commons.lang.StringUtils
 * @FileName StringUtil.java
 * @Language java
 * @date 2014-08-04
 * @author Daniel
 */
public class StringUtil extends StringUtils {

    //校验邮箱格式是否正确
    private static final String emailReg="^[a-zA-Z0-9][a-zA-Z0-9._-]*@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$";
    //校验手机号码是否正确
    private static final String phoneReg="^1\\d{10}$";
    //校验固定电话格式是否正确
    private static final String telReg="^0\\d{2,3}-?\\d{7,8}$";

    /**
     * 将一个字节数组转换为一个16进制形式的字符串。
     * 
     * @param input
     *            字节数组
     * @return 16进制形式的字符串
     */
    public static String toHex(byte[] input) {

        if (input == null)
            return null;
        StringBuffer output = new StringBuffer(input.length * 2);
        for (int i = 0; i < input.length; i++) {
            int current = input[i] & 0xff;
            if (current < 16)
                output.append("0");
            output.append(Integer.toString(current, 16));
        }

        return output.toString();
    }

    /**
     * 获得一个文本中标记间的文本字符串
     * @param text 一个文本字符串
     * @param tag 一个标记
     * @return 标记间的文本字符串
     */
    public static String getTagText(String text, String tag) {

        String ret = "";
        int startIndex = text.indexOf("<" + tag.trim() + ">");
        int endIndex = text.indexOf("</" + tag.trim() + ">");
        if ((startIndex >= 0) && (endIndex >= 0) && (startIndex + tag.length() + 2 < endIndex)) {
            ret = text.substring(startIndex + tag.length() + 2, endIndex).trim();
        }
        if(ret.indexOf("<![CDATA[") > -1){
            ret = StringUtils.substringBetween(ret, "<![CDATA[", "]]>");
        }
        return ret;
    }

    /**
     * 设置一个Xml文本中标记间的文本字符串
     * @param str 源Xml字符串
     * @param aTag 一个标记
     * @param value 值
     * @return 设置完成的Xml字符串
     */
    public static String setTagValue(String str, String aTag, String value) {

        StringBuilder sb = new StringBuilder();
        int startIndex = str.indexOf("<" + aTag.trim() + ">");
        int endIndex = str.indexOf("</" + aTag.trim() + ">");
        if ((startIndex >= 0) && (endIndex >= 0) && (startIndex + aTag.length() + 2 <= endIndex)) {
            sb.append(str.substring(0, startIndex + aTag.length() + 2));
            sb.append(value);
            sb.append(str.substring(endIndex));
        } else {
            startIndex = str.indexOf("<" + aTag.trim() + "/>");
            if (startIndex >= 0) {
                sb.append(str.substring(0, startIndex));
                sb.append("<" + aTag.trim() + ">");
                sb.append(value);
                sb.append("</" + aTag.trim() + ">");
                sb.append(str.substring(startIndex + ("<" + aTag.trim() + "/>").length()));
            }
        }
        return sb.toString();
    }

    /**
     * 获取一个32位的UUID
     * @return
     */
    public static synchronized String getUUID() {

        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    /**
     * 从字符串右边截取多少位字符
     * @param word 源字符串
     * @param size 位数
     * @return
     */
    public static String cutRightWord(String word, int size) {

        if (word.trim().length() >= size) {
            return StringUtils.right(word, size);
        }
        return word;
    }

    /**
     * 把字符串第一个字母转成小写字母
     * @param str
     * @return
     */
    public static String firstCharToLower(String str){
        String str1 = str.substring(0, 1);
        return str.replaceFirst(str1, str1.toLowerCase());
    }

    public static String firstCharToLower(Class<?> className){
        return firstCharToLower(className.getSimpleName());
    }


    public static String getIpAddr(HttpServletRequest request){

        String ip = request.getHeader("X-Forwarded-For");
        if(StringUtil.isNotEmpty(ip) && !"unknown".equalsIgnoreCase(ip)){
            //多次反向代理后会有多个ip值，第一个ip才是真实ip
            int index = ip.indexOf(",");
            if(index != -1){
                return ip.substring(0, index);
            }else {
                return ip;
            }
        }
        ip = request.getHeader("X-Real-IP");
        if(StringUtil.isNotEmpty(ip) && !"unknown".equalsIgnoreCase(ip)){
            return ip;
        }
        return request.getRemoteAddr();
    }

    public static boolean filterIp(String ip){
        boolean ret = true;
        String allowIp = Contants.PAY_REDPACK_ALLOW_IP;
        for(String s : allowIp.split(",")){
            if(s.equals(ip)){
                ret = false;
                break;
            }
        }
        return ret;
    }

    public static boolean filterTestIp(String ip){
        boolean ret = false;
        String allowIp = Contants.PAY_REDPACK_TEST_IP;
        for(String s : allowIp.split(",")){
            if(s.equals(ip)){
                ret = true;
                break;
            }
        }
        return ret;
    }

    /**
     * emoji表情转换(hex -> utf-16)
     * @param hexEmoji
     * @return
     */
    public static String emoji(int hexEmoji){
        return String.valueOf(Character.toChars(hexEmoji));
    }

    public static boolean isAgent(Integer level){
        List<Integer> levels = Arrays.asList(0, 1, 2, 3);
        return levels.contains(level);
    }

    public static boolean isCreateAgent(Integer level){
        List<Integer> levels = Arrays.asList(0, 1, 2);
        return levels.contains(level);
    }

    /**
     * 交易email格式是否正确
     * @return
     */
    public static boolean checkEmail(String email){
        if(isBlank(email)){return false;}
        Pattern pattern = Pattern.compile(emailReg);
        Matcher matcher = pattern.matcher(email);
        return matcher.matches();
    }
    /**
     * 交易手机号码格式是否正确
     * @return
     */
    public static boolean checkPhone(String phone){
        if(isBlank(phone)){return false;}
        Pattern pattern = Pattern.compile(phoneReg);
        Matcher matcher = pattern.matcher(phone);
        return matcher.matches();
    }
    /**
     * 交易固定电话格式是否正确
     * @return
     */
    public static boolean checkTel(String tel){
        if(isBlank(tel)){return false;}
        Pattern pattern = Pattern.compile(telReg);
        Matcher matcher = pattern.matcher(tel);
        return matcher.matches();
    }

    public static boolean isIE(HttpServletRequest request) {
        return (request.getHeader("USER-AGENT").toLowerCase().indexOf("msie") > 0
                || request.getHeader("USER-AGENT").toLowerCase().indexOf("rv:11.0") > 0
                || request.getHeader("USER-AGENT").toLowerCase().indexOf("edge") > 0) ? true
                : false;
    }
}
